<?php 
namespace app\common\model;
class Menu extends Common{
	protected function getPnameAttr($value,$data){
		return $data['pid'] ? $this->where("id",$data['pid'])->value("title") : '顶级菜单';
	}
	protected function getHidenameAttr($value, $data){
		$hides = [0=>'显示',1=>'隐藏'];
		return $hides[$data['hide']];
	}
	protected function getAlldataAttr($value, $data){
		$hides = [0=>'显示',1=>'隐藏'];
		$devs = [0=>'否',1=>'是'];
		$data['pname'] = $data['pid'] ? $this->where("id",$data['pid'])->value("title") : '顶级菜单';
		$data['hidename'] = $hides[$data['hide']];
		$data['devname'] = $devs[$data['is_dev']];
		return $data;
	}
	protected function getDevnameAttr($value, $data){
		if (empty($data)) {
			return false;
		}
		$devs = [0=>'否',1=>'是'];
		return $devs[$data['is_dev']];
	}
	public function save_data($data){
		$result = $this->validate(true)->allowField(true)->save($data);
		
		if($result!==false){
			$pk = $this->getPk();
			$id = $this->$pk;

			if(isset($data['child'])){
				$child = $data['child'];
				$urlarr = explode("/",$data['url']);
				foreach($child as $v){
					switch ($v) {
						case 'add':
							$this->add_child($id,"查看新增页面",$urlarr[0]."/add");
							$this->add_child($id,"新增动作",$urlarr[0]."/data_save");
							break;
						case 'edit':
							$this->add_child($id,"查看编辑页面",$urlarr[0]."/edit");
							$this->add_child($id,"更新动作",$urlarr[0]."/data_update");
							break;
						case 'delete':
							$this->add_child($id,"删除",$urlarr[0]."/data_delete");
							break;
						case 'cache':
							$this->add_child($id,"更新缓存",$urlarr[0]."/cache_data");
							break;
					}
				}
			}
			return $id;
		}
		return false;
	}
	public function add_child($pid,$title,$url){
		$data = [
			'pid' => $pid,
			'title' => $title,
			'url' => $url,
			'hide' => 1,
		];
		$this->insert($data);
	}
	public function delete_data($data){
		if (!is_array($data['item_ids'])) {
			$item_ids = explode(',', $data['item_ids']);
		}
		$ids = $this->get_allchild($item_ids, $item_ids);
		return $this::destroy($ids);
	}
	//获取所有下级菜单
	protected function get_allchild($pids, $pidarr=[]){
		$list = $this->where('pid', 'in', $pids)->order('id desc')->select();
		if (empty($list)) {
			return $pidarr;
		}
		$info = [];
		foreach ($list as $v) {
			$info[] = $v['id'];
			$pidarr[] = $v['id'];
		}
		return $this->get_allchild($info, $pidarr);
	}
}